<template>
  <section class="consumer">
    <el-col :span="24" class="action-bar">
      <el-input class="action-bar-input" placeholder="输入要查询的姓名" v-model="searchStr"></el-input>
      <el-button type="primary" size="medium" @click="getIntegralList">筛选</el-button>
      <el-button type="primary" size="medium" @click="dialogVisible=true">添加</el-button>
      <el-button type="primary" size="medium" @click="exportExcel">导出</el-button>
    </el-col>
    <!--列表-->
    <el-table :data="userList" highlight-current-row class="el-table-style">
      <!-- <el-table-column type="selection" width="55"/> -->
      <el-table-column type="index" width="60"/>
      <el-table-column prop="vip_card_nunmber" label="会员编号" width="180"/>
      <el-table-column prop="realname" label="姓名" width="120"/>
      <el-table-column prop="vip_level" label="会员级别" width="100"/>
      <el-table-column prop="integral_name" label="积分类型" width="100"/>
      <el-table-column prop="created_at" label="积分时间" width="180"/>
      <el-table-column prop="integral" label="积分" width="180"/>
      <el-table-column prop="integral_sum" label="总积分" width="180"/>
      <el-table-column prop="remark" label="备注" width="120"/>
      <el-table-column label="操作" width="250">
        <template slot-scope="scope">
          <el-button type="danger" size="mini" @click="integralListDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-col :span="24" class="footer-bar">
      <div class="page-code">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="pageTotal"
          :page-size="limit"
          @current-change="getIntegralList"
        ></el-pagination>
      </div>
    </el-col>

    <!-- 新增 -->
    <el-dialog :visible.sync="dialogVisible" @close="handleClose">
      <el-form :model="addForm" label-width="120px" ref="addForm">
        <el-form-item label="会员">
          <el-autocomplete
            v-model="autocompleteContent"
            :fetch-suggestions="querySearchAsync"
            placeholder="请输入内容"
            @select="handleSelect"
            style="width:300px"
          ></el-autocomplete>
        </el-form-item>
        <el-form-item label="积分类型">
          <el-select v-model="addForm.integral_rule" placeholder="请选择">
            <el-option
              v-for="item in integralRuleList"
              :key="item.value"
              :label="item.label"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="捐赠金额" v-if="donationFlag">
          <el-input v-model="addForm.money" type="number"></el-input>
        </el-form-item>
        <el-form-item label="发展会员等级" prop="level" width="100px" v-if="memberFlag">
							<el-select v-model="addForm.level" placeholder="请选择" >
								<el-option
									v-for="item in levelOptions"
									:key="item.code"
									:label="item.name"
									:value="item.id"
									>
								</el-option>
							</el-select>
						</el-form-item>
          <el-form-item label="积分">
            <div>{{addForm.integral}}</div>
            <!-- <el-input v-model="addForm.integral"></el-input> -->
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" :rows="4" placeholder="请输入内容" v-model="addForm.remark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitBtn">添加</el-button>
      </div>
    </el-dialog>
    <!-- 新增 end -->
  </section>
</template>

<script>
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
export default {
  data() {
    return {
			autocompleteContent: "",
      restaurants: [],//新增框搜索数据
      searchStr: "",
			userList: [],
			integralRuleList: [],
      dialogVisible: false, //弹窗
      pageTotal: 0,
			limit: 12,
			addForm:{
        vip_id:'',
        integral_rule:'',
				integral: '',
        remark: '',
        money:'',
        level:''
      },
      //会员级别
      levelOptions: [],
      donationFlag:'',//选中了捐赠
      memberFlag:''//选中了发展会员
    };
  },
  watch: {
    'addForm.vip_id':function(){
      this.getIntegralNum()
    },
    'addForm.integral_rule':function(nval){
      if(nval.type=='add_vip'){//发展会员
        this.memberFlag=true
      }else{
        this.memberFlag=false
      }

      if(nval.type=='donate'){//捐赠
        this.donationFlag=true
      }else{
        this.donationFlag=false
      }
      this.getIntegralNum()
    },
    "addForm.level"(nval){
      this.getIntegralNum()
    },
    "addForm.money"(nval){
      this.getIntegralNum()
    }
  },
  computed: {
    integral_rule_id(){
      return this.addForm.integral_rule.value
    }
  },
  methods: {
		 async getIntegralRuleList(){
      //获取积分规则列表
      const res=await this.$api.getIntegralRuleList()
      if(res.data.level=='success'){
				var list = res.data.data;
				var newList = [];
				list.forEach((item)=>{
					let obj = {};
					obj.label = item.name;
          obj.value = item.id;
          obj.type=item.type;
					newList.push(obj);
				})
				this.integralRuleList = newList;
			}
    },
		//新增提交按钮
		async submitBtn(){
			let params = {
				vip_id: this.addForm.vip_id,
				integral_rule_id: this.integral_rule_id,
				integral: this.addForm.integral,
        remark: this.addForm.remark,
        add_vip:this.addForm.level,
        donate:this.addForm.money
			}
      const res = await this.$api.addIntegralRecord(params);
      if(res.data.level=='success'){
				this.getIntegralList();
				this.dialogVisible = false;
				this.$message({
          message: res.data.message,
          type: 'success'
        });   
      }else{
        this.$message({
          message: res.data.message,
          type: 'warning'
        });
      }
		},
		//查询表单
    async querySearchAsync(queryString, cb) {
			let params = {
				key_word:queryString
      }
      const res = await this.$api.getUserVipList(params);
      if(res.data.level=='success'){
				let list = res.data.data.user_vip_list;
				let newList = [];
				list.forEach((item)=>{
					let obj = {};
					obj.vip_id = item.id; 
					obj.value = item.realname+ " - " + item.vip_name + " - " + item.phone;
					newList.push(obj);
				})
				cb(newList);      
      }else{
        this.$message({
          message: res.data.message,
          type: 'warning'
        });
      }
    },
    handleSelect(item) {
			//获得用户id
			this.addForm.vip_id = item.vip_id;
			this.autocompleteContent = item.value;
		},
    handleClose() {
			//编辑弹窗关闭前的回调
			this.initData();
    },
    async getIntegralList(page) {
      var params = {
        limit: this.limit,
        page: page || 1,
        keyword: this.searchStr
      };
      //获取积分列表
      const res = await this.$api.getIntegralList(params);
      if (res.data.level == "success") {
        this.userList = res.data.data;
        this.pageTotal = res.data.page_info.total;
      }
    },
    integralListDelete(id) {
      //删除积分记录
      const judge = this.$confirm("删除该积分记录?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const res = await this.$api.deleteIntegralRecord({ id });
          if (res.data.level == "success") {
            this.getIntegralList();
            this.$message({
              type: "success",
              message: res.data.message
            });
          } else {
            this.$message({
              type: "error",
              message: res.data.message
            });
          }
        })
        .catch(() => {});
    },
    async getIntegralNum(){
      //获取积分
      const res=await this.$api.getIntegralNum({
        vip_id:this.addForm.vip_id,
        integral_rule_id:this.integral_rule_id,
        money:this.addForm.money,
        vip_rule_id :this.addForm.level
      })
      if(res.data.level=='success'){
        this.addForm.integral=res.data.data;
      }else{
        this.addForm.integral='';
      }
    },
    async getUserVipRule(){
      //获取会员等级&缴费规则接口
      const data=await this.$api.getUserVipRule();
      if(data.data.level=='success'){
        this.levelOptions= data.data.data.vip_list
      }
    },
    exportExcel(){
      const judge= this.$confirm('导出积分列表？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
        }).then(async() => {
          const res=await this.$api.getIntegralList({})
          if(res.data.level == 'success'){
            let List=res.data.excel_data
            let arr=List.map(val=>{
              let obj={};
              obj['会员编号']=val.vip_card_nunmber;
              obj['姓名']=val.realname;
              obj['会员级别']=val.vip_level;
              obj['积分类型']=val.integral_name;
              obj['积分时间']=val.created_at;
              obj['积分']=val.integral;
              obj['总积分']=val.integral_sum;
              obj['备注']=val.remark;
              return obj
            })
            this.exportExcelHandle(arr);
            this.$message({
              type: 'success',
              message: res.data.message
            });
          }else{
            this.$message({
              type: 'error',
              message: res.data.message
            });
          }
        }).catch(() => {
          
      });
	  },
    exportExcelHandle(data){
      let ws = XLSX.utils.json_to_sheet(data);
      let wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, "会员");
      var wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
      try {
        FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), 'sheetjs.xlsx')
      } catch (e) { if (typeof console !== 'undefined') console.log(e, wbout) }
      return wbout
    },
    initData() {
      this.addForm = {
        vip_id:'',
        integral_rule:'',
        integral: '',
        remark: '',
      }
      this.autocompleteContent = "";
    }
  },
  mounted() {
		this.getIntegralList();
    this.getIntegralRuleList();
    this.getUserVipRule();
  }
};
</script>
<style lang='scss' scoped>
.consumer {
  .task-form-text {
    color: #666666;
  }
  .action-bar {
    background-color: #f2f2f2;
    height: 60px;
    margin: 10px 0px;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    padding-left: 20px;
    .action-bar-input {
      width: 250px;
      margin-right: 14px;
    }
  }
  .el-table-style {
    width: 100%;
    border: 1px solid #f2f2f2;
  }
  .footer-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: #f2f2f2;
    padding: 8px;
    margin: 10px 0px;
    box-sizing: border-box;
  }
  .dialog-footer {
    text-align: center;
  }
	.autocomplete{
		width: 100%;
	}
}
</style>

<style>
.el-pagination.is-background .el-pager li,
.el-pagination.is-background .btn-prev,
.el-pagination.is-background .btn-next {
  background-color: #fff;
  border: 1px solid #f1f1f1;
  margin: 0;
}

.consumer .el-dialog__body {
  overflow: auto;
}
</style>
